﻿using System.Collections.Concurrent;

namespace ZYing.QPanel.Impl
{
    public partial class InProcExecutionHistoryStore
    {
        private class NodeCollection
        {
            private readonly ConcurrentDictionary<string, Node> _map = new ConcurrentDictionary<string, Node>();
            private readonly ConcurrentQueue<Node> _queue = new ConcurrentQueue<Node>();
            public bool TryGetNode(string fireInstanceId, out Node node) => _map.TryGetValue(fireInstanceId, out node);
            public Node Add(ExecutionHistoryEntry entry)
            {
                var add = new Node(entry);
                if (_map.TryAdd(entry.FireInstanceId, add))
                {
                    _queue.Enqueue(add);
                    while (_queue.Count > Limit && _queue.TryDequeue(out var remove))
                    {
                        _map.TryRemove(remove.Id, out _);
                    }
                }
                return add;
            }
        }
    }
}
